# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '11153': {  # loki  支付宝  1-5000
        'API_KEY': 'c9a8cc72f79329dea39312cfa0a61fb9',
        'gateway': 'http://payapi.3vpay.net/pay',
        'query_gateway': 'http://payapi.3vpay.net/pay/tradeQuery',
    },
    '11247': {  # dwc 支付方式：支付宝3.5%，10---5000.t1结算。
        'API_KEY': '49b442bdbb7a7bf718efd30e81b40fdc',
        'gateway': 'http://payapi.3vpay.net/pay',
        'query_gateway': 'http://payapi.3vpay.net/pay/tradeQuery',
    },
    '11277': {  # witch 单笔限额：支付宝3.5%，银联1.7%。单笔都是5---5000.d1结算。。
        'API_KEY': '0981d063754d9074f5e78ea2e6fccd72',
        'gateway': 'http://payapi.3vpay.net/pay',
        'query_gateway': 'http://payapi.3vpay.net/pay/tradeQuery',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    '''  生成下单签名 '''
    s = 'partnerId={}&timeStamp={}&totalFee={}&key={}'.format(
        parameter['partnerId'], parameter['timeStamp'], parameter['totalFee'], key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest()
    _LOGGER.info(u'v3pay origin string: %s, sign:%s', s, sign)
    return sign


def generate_query_sign(parameter, key):
    '''  生成查询签名 '''
    s = 'partnerId={}&timeStamp={}&totalFee={}&key={}'.format(
        parameter['partnerId'], parameter['timeStamp'], parameter['totalFee'], key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest()
    _LOGGER.info(u'v3pay origin  query string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    s = 'channelOrderId={}&key={}&orderId={}&timeStamp={}&totalFee={}'.format(
        params['channelOrderId'], key, params['orderId'], params['timeStamp'], params['totalFee'])
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest()
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("v3pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_sign(params, key):
    sign = params['signMsg']
    params.pop('signMsg')
    s = 'merOrdId={}&merOrdAmt={}&merId={}&sysOrdId={}&tradeStatus={}&merKey={}'.format(
        params['merOrdId'], params['merOrdAmt'], params['merId'], params['sysOrdId'], params['tradeStatus'],
        key)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest()
    if sign != calculated_sign:
        _LOGGER.info("v3pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 微信H5:  101 
# 微信正扫码：102
# 微信反扫码：103
# QQ正扫码：104
# QQ反扫码：105
# QQ WAP：106
# 支付宝正扫码：107
# 支付宝反扫码：108
# 支付宝WAP：109
# 银联反扫码：110
# 银联正扫码：111
# 银联快捷支付：112
# 银联WAP：113
# 网关支付：114
def _get_paytype(pay_type):
    if pay_type == 'wxpay':
        return '101'
    elif pay_type == 'qq':
        return '106'
    elif pay_type == 'alipay':
        return '109'
    elif pay_type == 'quick':
        return '112'
    elif pay_type == 'quick_wap':
        return '113'
    else:
        return '113'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('partnerId', app_id),
        ('channelOrderId', str(pay.id)),
        ('timeStamp', str(int(time.time()))),
        ('body', 'book'),
        ('totalFee', str(int(pay_amount * 100))),
        ('payType', _get_paytype(service)),
        ('notifyUrl', '{}/pay/api/{}/v3pay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnUrl', '{}/pay/api/{}/v3pay/{}'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
    ))
    p_dict['sign'] = generate_sign(p_dict, api_key)
    _LOGGER.info('v3pay create_charge data : %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('v3pay create_charge rsp : %s', response.text)
    j = json.loads(response.text)['payParam']
    order_db.fill_third_id(pay.id, j['orderId'])
    return {'charge_info': j['pay_info']}


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    _LOGGER.info("v3pay notify data: %s", data)
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['channelOrderId']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('v3pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['return_code'])
    mch_id = pay.mch_id
    trade_no = data.get('orderId')
    total_fee = float(data['totalFee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0000':
        _LOGGER.info('v3pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    charge_resp = {}
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('partnerId', app_id),
        ('orderId', str(pay_order.third_id)),
        ('timeStamp', str(int(time.time()))),
        ('totalFee', str(int(pay_order.total_fee * 100))),
    ))
    p_dict['sign'] = generate_query_sign(p_dict, api_key)
    _LOGGER.info('v3pay query_charge data : %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3)
    _LOGGER.info('v3pay query_charge rsp : %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)['return_content']
        trade_status = str(data['return_code'])
        if trade_status == '0000':
            trade_no = data.get('orderId')
            total_fee = float(data['totalFee']) / 100.0
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }
            _LOGGER.info('v3pay query order success, mch_id:%s pay_id:%s',
                         pay_order.mch_id, pay_order.id)
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('v3pay data error, status_code: %s', response.status_code)
    return charge_resp
